<template>
  <div class="manufacturing-dashboard" :class="{ 'dark-mode': isDarkMode }">
    <a-row :gutter="[20, 20]">
      <a-col :span="24">
        <a-row justify="end">
          <a-button 
            :type="isDarkMode ? 'primary' : 'default'" 
            @click="toggleTheme"
          >
            {{ isDarkMode ? '切换至亮色模式' : '切换至暗色模式' }}
          </a-button>
        </a-row>
      </a-col>
    </a-row>

    <!-- 顶部统计卡片 -->
    <a-row :gutter="[20, 20]" class="panel-group">
      <a-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
        <a-card :loading="loading" :bordered="false" class="dashboard-card card-1" hoverable>
          <template #cover>
            <div class="card-header">
              <file-outlined class="card-icon" />
              <div class="card-meta">
                <div class="card-title">今日工单</div>
                <count-to :startVal="0" :endVal="workorderCount.today" :duration="2600" class="card-num" />
                <div class="card-percent"><span class="up">20</span></div>
              </div>
            </div>
          </template>
          <a-progress :percent="(workorderCount.today / 20) * 100" :showInfo="false" status="active" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
        <a-card :loading="loading" :bordered="false" class="dashboard-card card-2" hoverable>
          <template #cover>
            <div class="card-header">
              <schedule-outlined class="card-icon" />
              <div class="card-meta">
                <div class="card-title">生产计划</div>
                <count-to :startVal="0" :endVal="planCount.total" :duration="2600" class="card-num" />
                <div class="card-percent"><span class="up">11</span></div>
              </div>
            </div>
          </template>
          <a-progress :percent="(planCount.ongoing / planCount.total) * 100" :showInfo="false" status="active" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
        <a-card :loading="loading" :bordered="false" class="dashboard-card card-3" hoverable>
          <template #cover>
            <div class="card-header">
              <shopping-outlined class="card-icon" />
              <div class="card-meta">
                <div class="card-title">待入库</div>
                <count-to :startVal="0" :endVal="inboundCount.pending" :duration="2600" class="card-num" />
                <div class="card-percent"> <span class="down">1</span></div>
              </div>
            </div>
          </template>
          <a-progress :percent="(inboundCount.pending / 20) * 100" :showInfo="false" status="active" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
        <a-card :loading="loading" :bordered="false" class="dashboard-card card-4" hoverable>
          <template #cover>
            <div class="card-header">
              <pie-chart-outlined class="card-icon" />
              <div class="card-meta">
                <div class="card-title">合格率</div>
                <count-to :startVal="0" :endVal="qualityRate" :duration="2600" class="card-num" suffix="%" />
                <div class="card-percent">较上月 <span class="up">+0.8%</span></div>
              </div>
            </div>
          </template>
          <a-progress :percent="qualityRate" :showInfo="false" status="active" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 中间图表区域 -->
    <a-row :gutter="[20, 20]" class="chart-row">
      <a-col :xs="24" :sm="24" :md="16" :lg="16">
        <a-card class="chart-card" :loading="loading" :bordered="false" :title="'生产计划执行趋势'">
          <template #extra>
            <a-radio-group v-model:value="planChartType" button-style="solid" size="small">
              <a-radio-button value="week">周</a-radio-button>
              <a-radio-button value="month">月</a-radio-button>
            </a-radio-group>
          </template>
          <div class="chart-container">
            <production-trend-chart :chart-data="planTrendData" :chart-type="planChartType" :theme="isDarkMode ? 'dark' : 'light'" />
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="24" :md="8" :lg="8">
        <a-card class="chart-card" :loading="loading" :bordered="false" :title="'工单状态分布'">
          <div class="chart-container">
            <workorder-status-chart :chart-data="workorderStatusData" :theme="isDarkMode ? 'dark' : 'light'" />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[20, 20]" class="chart-row">
      <a-col :xs="24" :sm="24" :md="12" :lg="12">
        <a-card class="chart-card" :loading="loading" :bordered="false" :title="'物料库存水平Top10'">
          <div class="chart-container">
            <material-stock-chart :chart-data="materialStockData" :theme="isDarkMode ? 'dark' : 'light'" />
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="24" :md="12" :lg="12">
        <a-card class="chart-card" :loading="loading" :bordered="false" :title="'入库申请趋势'">
          <div class="chart-container">
            <inbound-trend-chart :chart-data="inboundTrendData" :theme="isDarkMode ? 'dark' : 'light'" />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 底部数据表格 -->
    <a-row :gutter="[20, 20]" class="table-row">
      <a-col :xs="24" :sm="24" :md="12" :lg="12">
        <a-card class="table-card" :loading="loading" :bordered="false" :title="'最近工单'">
          <template #extra>
            <a-button type="link" @click="goToWorkorder">更多</a-button>
          </template>
          <a-table
            :dataSource="recentWorkorders"
            :columns="workorderColumns"
            :pagination="false"
            size="small"
            :rowKey="record => record.orderCode"
          />
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="24" :md="12" :lg="12">
        <a-card class="table-card" :loading="loading" :bordered="false" :title="'待处理入库申请'">
          <template #extra>
            <a-button type="link" @click="goToInbound">更多</a-button>
          </template>
          <a-table
            :dataSource="pendingInbounds"
            :columns="inboundColumns"
            :pagination="false"
            size="small"
            :rowKey="record => record.applyCode"
          />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup name="Index">
import { ref, onMounted, reactive, computed, h, createVNode, watch } from 'vue';
import CountTo from 'vue3-count-to';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  FileOutlined,
  ScheduleOutlined,
  ShoppingOutlined,
  PieChartOutlined
} from '@ant-design/icons-vue';

// 导入图表组件
import ProductionTrendChart from "@/components/Charts/ProductionTrendChart";
import WorkorderStatusChart from "@/components/Charts/WorkorderStatusChart";
import MaterialStockChart from "@/components/Charts/MaterialStockChart";
import InboundTrendChart from "@/components/Charts/InboundTrendChart";

// 导入API服务 - 暂时不使用API
import request from '@/utils/request';

// 引入工单API
import { listWorkorder } from '@/api/pm/workorder';
import { listMaterialInboundApply } from '@/api/tas/materialInboundApply';

// 主题模式
const isDarkMode = ref(false);
const loading = ref(true);

// 图表类型选择
const planChartType = ref('week');
const router = useRouter();

// 统计数据 - 使用写死的数据
const workorderCount = reactive({
  today: 8,
  week: 42,
  total: 156
});

const planCount = reactive({
  ongoing: 15,
  completed: 68,
  total: 83
});

const inboundCount = reactive({
  pending: 12,
  today: 7,
  total: 245
});

const qualityRate = ref(98.5);

// 图表数据
const planTrendData = reactive({
  week: {
    dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    planned: [5, 8, 6, 9, 7, 3, 4],
    completed: [4, 6, 5, 8, 7, 3, 2]
  },
  month: {
    dates: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    planned: [30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85],
    completed: [28, 32, 38, 42, 48, 50, 55, 60, 65, 70, 75, 80]
  }
});

const workorderStatusData = reactive([
  { value: 35, name: '进行中' },
  { value: 45, name: '已完成' },
  { value: 15, name: '未开始' },
  { value: 5, name: '已取消' }
]);

const materialStockData = reactive([
  { name: '螺丝M4', value: 1256 },
  { name: '轴承606', value: 856 },
  { name: '电容100uF', value: 756 },
  { name: '风扇12cm', value: 687 },
  { name: '铝板2mm', value: 587 },
  { name: '电阻10K', value: 498 },
  { name: '开关按钮', value: 456 },
  { name: 'LED灯珠', value: 387 },
  { name: '导线红色', value: 298 },
  { name: '散热片', value: 156 }
]);

const inboundTrendData = reactive({
  months: ['1月', '2月', '3月', '4月', '5月', '6月'],
  purchase: [12, 19, 15, 22, 18, 20],
  production: [8, 10, 12, 9, 11, 7],
  return: [5, 3, 4, 6, 2, 4]
});

// 最近工单 - 从后端获取
const recentWorkorders = ref([]);

// 工作台列
const workorderColumns = [
  {
    title: '工单编号',
    dataIndex: 'orderCode',
    key: 'orderCode',
    width: 170
  },
  {
    title: '关联计划',
    dataIndex: 'planName',
    key: 'planName',
    width: 180
  },
  {
    title: '产品',
    dataIndex: 'productName',
    key: 'productName'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    customRender: ({ text }) => {
      const statusMap = {
        '0': { color: 'blue', text: '未开始' },
        '1': { color: 'orange', text: '进行中' },
        '2': { color: 'green', text: '已完成' },
        '3': { color: 'red', text: '已取消' }
      };
      const config = statusMap[text] || { color: 'default', text: '未知' };
      return h('a-tag', { color: config.color }, config.text);
    }
  }
];

// 待处理入库申请 - 使用真实数据
const pendingInbounds = ref([]);

// 入库申请列
const inboundColumns = [
  {
    title: '申请编号',
    dataIndex: 'applyCode',
    key: 'applyCode',
    width: 120
  },
  {
    title: '申请人',
    dataIndex: 'applyUserName',
    key: 'applyUserName'
  },
  {
    title: '申请时间',
    dataIndex: 'applyTime',
    key: 'applyTime'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  }
];

// 主题切换
function toggleTheme() {
  isDarkMode.value = !isDarkMode.value;
  document.body.classList.toggle('dark-theme', isDarkMode.value);
}

// 页面跳转
function goToWorkorder() {
  router.push('/pm/workorder');
}

function goToInbound() {
  router.push('/tas/MaterialInboundApply');
}

// 获取待处理入库申请
async function getPendingInbounds() {
  try {
    const response = await listMaterialInboundApply({
      pageNum: 1,
      pageSize: 5,
      status: '0'  // 待处理状态
    });
    
    if (response.code === 200 && response.rows) {
      pendingInbounds.value = response.rows.map(item => ({
        applyCode: item.applyCode,
        applyType: item.applyType,
        applyUserName: item.applyUserName,
        applyTime: item.applyTime,
        status: '待处理'
      }));
    } else {
      // 如果API调用成功但没有数据，使用默认值
      useFallbackPendingInbounds();
    }
  } catch (error) {
    console.error('获取待处理入库申请失败:', error);
    // 如果API调用失败，使用默认值
    useFallbackPendingInbounds();
  }
}

// 使用默认的待处理入库申请数据
function useFallbackPendingInbounds() {
  pendingInbounds.value = [
    { applyCode: 'IN20231201', applyTypeName: '采购入库', applyUserName: '张三', applyTime: '2023-12-01', status: '待处理' },
    { applyCode: 'IN20231202', applyTypeName: '生产入库', applyUserName: '李四', applyTime: '2023-12-02', status: '待处理' },
    { applyCode: 'IN20231203', applyTypeName: '采购入库', applyUserName: '王五', applyTime: '2023-12-03', status: '待处理' },
    { applyCode: 'IN20231204', applyTypeName: '生产入库', applyUserName: '赵六', applyTime: '2023-12-04', status: '待处理' }
  ];
}

// 初始化数据
onMounted(() => {
  loading.value = true;
  
  // 同时获取最近工单数据和待处理入库申请
  Promise.all([
    getRecentWorkorders(),
    getPendingInbounds()
  ]).finally(() => {
    // 移除loading状态
    setTimeout(() => {
      loading.value = false;
    }, 1000);
    
    console.log('数据看板已加载');
  });
});

// 获取最近工单数据
function getRecentWorkorders() {
  listWorkorder({
    pageNum: 1,
    pageSize: 5,  // 只获取4条最新数据
    orderByColumn: 'createTime',  // 按创建时间排序
    isAsc: 'desc'  // 降序，最新的在前
  }).then(response => {
    if (response.code === 200 && response.rows) {
      // 将后端数据映射到我们需要的格式
      recentWorkorders.value = response.rows.map(item => {
        return {
          orderCode: item.orderCode,
          planName: item.planName || '未关联计划',
          productName: item.productName || '未知产品',
          status: item.status
        };
      });
    }
  });
}

// 注释掉或删除API部分，只保留写死的数据
/* 
// API接口函数
async function getDashboardData() {
  // API服务暂时未实现，不使用此函数
}

// 获取计划趋势数据
async function getPlanTrendData() {
  // API服务暂时未实现，不使用此函数
}

// 监听计划图表类型变化，重新获取数据
watch(() => planChartType.value, async () => {
  loading.value = true;
  // 切换已有的本地数据即可，不需要API调用
  loading.value = false;
});
*/
</script>

<style lang="scss" scoped>
.manufacturing-dashboard {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
  transition: all 0.3s;
  
  &.dark-mode {
    background-color: #141414;
    color: rgba(255, 255, 255, 0.85);
    
    .card-title {
      color: rgba(255, 255, 255, 0.85) !important;
    }
    
    .dashboard-card {
      background-color: #1f1f1f;
      border-color: #303030;
      
      .card-num {
        color: rgba(255, 255, 255, 0.85) !important;
      }
      
      .card-meta {
        color: rgba(255, 255, 255, 0.85);
      }
      
      .card-percent {
        color: rgba(255, 255, 255, 0.65) !important;
        
        .up {
          color: #52c41a !important;
        }
        
        .down {
          color: #ff4d4f !important;
        }
      }
    }
    
    .chart-card, .table-card {
      background-color: #1f1f1f;
      border-color: #303030;
      
      .ant-card-head {
        color: rgba(255, 255, 255, 0.85);
        border-color: #303030;
        
        .ant-card-head-title {
          color: rgba(255, 255, 255, 0.85);
        }
      }
      
      .ant-table {
        background-color: transparent;
        color: rgba(255, 255, 255, 0.85);
        
        .ant-table-thead > tr > th {
          background-color: #1f1f1f;
          color: rgba(255, 255, 255, 0.85);
          border-color: #303030;
        }
        
        .ant-table-tbody > tr > td {
          border-color: #303030;
          color: rgba(255, 255, 255, 0.85);
        }
        
        .ant-table-tbody > tr:hover > td {
          background-color: #303030;
        }
      }
    }
    
    .ant-progress-bg {
      background-color: #177ddc;
    }
    
    a {
      color: #177ddc;
    }
  }
  
  .panel-group {
    margin-bottom: 20px;
    
    .dashboard-card {
      border-radius: 8px;
      overflow: hidden;
      transition: all 0.3s;
      
      .card-header {
        display: flex;
        align-items: center;
        padding: 20px;
      }
      
      .card-icon {
        font-size: 36px;
        padding: 10px;
        border-radius: 8px;
        margin-right: 15px;
      }
      
      .card-meta {
        flex: 1;
      }
      
      .card-title {
        font-size: 16px;
        color: rgba(0, 0, 0, 0.45);
        margin-bottom: 8px;
      }
      
      .card-num {
        font-size: 28px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
        line-height: 1.2;
        margin-bottom: 5px;
      }
      
      .card-percent {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        
        .up {
          color: #52c41a;
          font-weight: 500;
        }
        
        .down {
          color: #ff4d4f;
          font-weight: 500;
        }
      }
      
      &.card-1 .card-icon {
        background-color: rgba(24, 144, 255, 0.1);
        color: #1890ff;
      }
      
      &.card-2 .card-icon {
        background-color: rgba(82, 196, 26, 0.1);
        color: #52c41a;
      }
      
      &.card-3 .card-icon {
        background-color: rgba(250, 140, 22, 0.1);
        color: #fa8c16;
      }
      
      &.card-4 .card-icon {
        background-color: rgba(247, 89, 64, 0.1);
        color: #f75940;
      }
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      border-radius: 8px;
      height: 350px;
      
      .chart-container {
        position: relative;
        width: 100%;
        height: 280px;
      }
    }
  }
  
  .table-row {
    margin-bottom: 20px;
    
    .table-card {
      border-radius: 8px;
    }
  }
}

@media (max-width: 768px) {
  .manufacturing-dashboard {
    .dashboard-card {
      .card-header {
        flex-direction: column;
        text-align: center;
        
        .card-icon {
          margin-right: 0;
          margin-bottom: 10px;
        }
      }
    }
    
    .chart-row .chart-card {
      height: auto;
      
      .chart-container {
        height: 220px;
      }
    }
  }
}
</style>

